# get some sample users. To check the user activities.

require "dbm"
require "00_common"


module UserSample
  def self.get_all_db_files
  	Common.get_all_files("./db_files")
  end

  def self.get_10_sample_users(db_file)
    puts "to get samples:get_10_sample_users"
    sample_db = DBM.open "./db_files/" + db_file[0, db_file.length - 3]

    puts "to get first 10 keys"
    sample_users = []

    counter  = 0
    sample_db.each do |key, value|
      if counter < 100
        puts key
        sample_users << key
        counter = counter + 1
      else
        break
      end
    end

    sample_db.close
    sample_users
  end

  def self.search_sample_users(db, sample_users, user_mapping)
  	sample_users.each do |user_key|
  	  if db[user_key]
  	  	if user_mapping[user_key]
          user_mapping[user_key] = user_mapping[user_key] + "$|$" + db[user_key]
        else
          user_mapping[user_key] = db[user_key]
        end
  	  end
  	end
  end

  def self.output_sample(user_mapping)
    output_file = File.open "user_samples.txt", "w"
    user_mapping.each do |key, value|
      lines = value.split "$|$"

      output_file.puts key + ":#{lines.size} " + "=" * 20
      lines.each do |line|
        fields = line.split "|"
        # LOCAL_TIME_STAMP    = 1
        # SESSION_ID          = 2
        # SESSION_START_TIME  = 3
        # CLIENT_IP           = 4
        # SERVER_IP           = 5
        # L4_PROTO            = 6
        # CLIENT_PORT         = 7
        # SERVER_PORT         = 8
        # CLIENT_PAYLOAD_HEX  = 9
        # SERVER_PAYLOAD_HEX  = 10
        # PROTOCOL            = 11
        # CLIENT_PAYLOAD      = 12
        # SERVER_PAYLOAD      = 13

        output_file.puts "#{fields[LOCAL_TIME_STAMP]}|#{fields[SESSION_ID]}"
      end
    end
  end
end


begin
  all_user_db_files = UserSample.get_all_db_files
  puts "to get sample users:"
  sample_users = UserSample.get_10_sample_users all_user_db_files[0]

  puts "sample users are:"
  puts sample_users.join "\n"

  user_mapping = Hash.new

  all_user_db_files.each do |db_file_name|
    db = DBM.open "./db_files/" + db_file_name[0, db_file_name.length - 3]
  	UserSample.search_sample_users(db, sample_users, user_mapping)
    db.close
  end

  UserSample.output_sample user_mapping
rescue Exception => e
	puts e.to_s
end